﻿using Framework.Domain.Enum;
using Framework.Domain.Model;
using Framework.Infrastructure;
using Framework.Infrastructure.RabbitMQ;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Framework.MVC.Infrastructure.Filters
{
    /// <summary>
    /// 异常过滤器（系统抛错时记录日志并返回特定格式的JSON）
    /// </summary>
    [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
    public class LogExceptionAttribute : HandleErrorAttribute
    {
        /// <summary>
        /// 处理未处理的异常
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnException(ExceptionContext filterContext)
        {
            if (!filterContext.ExceptionHandled)
            {
                string controllerName = (string)filterContext.RouteData.Values["controller"];
                string actionName = (string)filterContext.RouteData.Values["action"];
                string param = Common.GetPostParas();
                string ip = Common.GetIp();
                //LogManager.GetLogger("LogExceptionAttribute").Error("Location：{0}/{1} Param：{2}UserIP：{3} Exception：{4}", controllerName, actionName, param, ip, filterContext.Exception.Message);
                //NLogHelper.Error(string.Format("Location：{0}/{1} Param：{2}UserIP：{3} Exception：{4}", controllerName, actionName, param, ip, filterContext.Exception.Message));

                //异常日志入库（消息队列）
                RabbitPublisher.Publish(new RabbitModel_Base { ModelType = RabbitModel_Enum.ExceptionLog, ExceptionLog = new SYS_ExceptionLog { UserIP = ip, EptLevel = LogLevel.Error, Location = string.Format("{0}/{1}", controllerName, actionName), Params = param, Exception = filterContext.Exception.Message } });

                filterContext.Result = new JsonResult
                {
                    Data = new ReturnModel_Common { success = false, code = ReturnCode_System.服务端抛错, msg = /*filterContext.Exception.Message*/"SYSTEM ERROR" },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            if (filterContext.Result is JsonResult)
                filterContext.ExceptionHandled = true;//返回结果是JsonResult，则设置异常已处理
            else
                base.OnException(filterContext);//执行基类HandleErrorAttribute的逻辑，转向错误页面
        }

    }
}